<template>
  <div class="container">
    <el-row :gutter="10">
      <el-col :span="5">
        <div class="card-container">
          <el-card :body-style="{ padding: '10px' }" shadow="never">
            <template #header>
              <div class="card-header">
                <el-row :gutter="10" style="width: 100%" align="middle">
                  <el-col :span="6">
                    <span class="card-title">组织</span>
                  </el-col>
                  <el-col :span="18">
                    <div class="card-btn">
                      <div>
                        <el-button
                          icon="Remove"
                          v-auth="['dept/sc']"
                          type="warning"
                          @click="handleDeptDelete"
                        >
                          删除
                        </el-button>
                      </div>
                      <div>
                        <el-tooltip
                          content="点击新增后请在右侧输入内容后保存"
                          placement="right"
                        >
                          <el-button
                            icon="Plus"
                            v-auth="['dept/xz']"
                            type="primary"
                            @click="handleDeptAdd"
                          >
                            新增
                          </el-button>
                        </el-tooltip>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </template>
            <div class="card-content-full">
              <el-scrollbar>
                <div style="display: flex; align-items: center">
                  <el-input
                    v-model="state.searchKey"
                    clearable
                    placeholder="输入名称/编码搜索部门"
                    prefix-icon="search"
                  />
                  <el-button
                    type="primary"
                    icon="search"
                    @click="handleSearchQuery"
                  />
                </div>
                <el-tree
                  ref="deptTreeRef"
                  v-loading="deptTree.loading"
                  :check-strictly="true"
                  class="custom-tree"
                  :data="deptTree.dataList"
                  highlight-current
                  node-key="id"
                  lazy
                  :load="lazyLoadNode"
                  :props="deptTree.props"
                  :show-checkbox="true"
                  @node-click="handleNodeClick"
                >
                  <template #default="{ node, data }">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="data.deptFullName"
                      placement="top"
                    >
                      <span>{{ node.label }}</span>
                    </el-tooltip>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="19">
        <el-tabs
          ref="tabsRef"
          v-model="state.currentTabs"
          :stretch="true"
          type="border-card"
        >
          <el-tab-pane label="组织信息" name="0">
            <template #label>
              <span>
                <i class="el-icon-message">组织信息</i>
              </span>
            </template>
            <el-form
              ref="deptFormRef"
              label-position="left"
              label-width="80px"
              :model="state.deptFormData"
              :rules="state.deptFormRules"
            >
              <el-form-item label="组织名称" prop="deptName">
                <el-input
                  v-model="state.deptFormData.deptName"
                  placeholder="组织名称"
                  @change="handleDeptNameChange"
                />
              </el-form-item>
              <el-form-item label="组织编码" prop="deptCode">
                <el-input
                  v-model="state.deptFormData.deptCode"
                  placeholder="组织编码"
                  style="width: 60%"
                />
                <el-radio-group v-model="state.deptFormData.codeAsId">
                  <el-radio label="新增时编码即为ID" :value="true" />
                  <el-radio label="新增时ID自动填充" :value="false" />
                </el-radio-group>
              </el-form-item>
              <el-form-item label="组织类型" prop="deptType">
                <DictSelect
                  ref="deptTypeRef"
                  v-model:defaultValue="state.deptFormData.deptType"
                  dict-code="1007"
                  show-all="N"
                  @change="handleDeptTypeChange"
                />
              </el-form-item>
              <el-form-item label="办公电话">
                <el-input
                  v-model="state.deptFormData.tel"
                  placeholder="办公电话"
                />
              </el-form-item>
              <el-form-item label="办公地址">
                <el-input
                  v-model="state.deptFormData.address"
                  placeholder="办公地址"
                />
              </el-form-item>
              <el-form-item label="排序号">
                <el-input
                  v-model="state.deptFormData.orderId"
                  placeholder="排序号"
                />
              </el-form-item>
              <el-form-item label="上级组织">
                <el-input
                  v-model="state.deptFormData.parentDeptName"
                  :disabled="true"
                  placeholder="请选择上级组织"
                  style="width: 200px"
                >
                  <template #append>
                    <el-button icon="Search" @click="openDeptSelector" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="部门领导">
                <el-input
                  v-model="state.deptFormData.leaderUserName"
                  :disabled="true"
                  placeholder="请选择部门领导"
                  style="width: 200px"
                >
                  <template #append>
                    <el-button
                      icon="Search"
                      @click="handleOpenLeaderUserPicker"
                    />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="state.deptFormData.remark"
                  placeholder="备注"
                />
              </el-form-item>
              <el-button
                icon="DocumentChecked"
                v-auth="['dept/xg']"
                type="primary"
                @click="onDeptSaveSubmit()"
              >
                保存
              </el-button>
            </el-form>
          </el-tab-pane>
          <el-tab-pane name="1">
            <template #label>
              <span>
                <i class="el-icon-user">组织人员</i>
                <el-badge size="mini" :value="staffTable.pagination.total" />
              </span>
            </template>
            <vab-query-form>
              <vab-query-form-top-panel>
                <el-form
                  :inline="true"
                  label-width="0px"
                  :model="staffTable.queryForm"
                >
                  <el-row :gutter="5">
                    <el-col :span="5">
                      <el-input
                        v-model="staffTable.queryForm.userName"
                        placeholder="员工姓名"
                      />
                    </el-col>
                    <el-col :span="5">
                      <el-input
                        v-model="staffTable.queryForm.labor"
                        placeholder="工号"
                      />
                    </el-col>
                    <el-col :span="5">
                      <el-input
                        v-model="staffTable.queryForm.mobilePhone"
                        placeholder="手机号"
                      />
                    </el-col>
                    <el-col :span="4">
                      <DictSelect
                        :default-value="staffTable.queryForm.status"
                        dict-code="1031"
                        @change="handleStatusChange"
                      />
                    </el-col>
                    <el-col :span="5" style="text-align: right">
                      <el-button
                        icon="refresh-left"
                        type="warning"
                        @click="handleResetQuery"
                      >
                        重置
                      </el-button>
                      <el-button
                        icon="Search"
                        type="primary"
                        @click="queryTableData"
                      >
                        查询
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form>
              </vab-query-form-top-panel>
              <vab-query-form-left-panel :span="24">
                <el-button
                  v-auth="['dept/zzryxz']"
                  icon="circle-plus"
                  type="primary"
                  @click="handleStaffAdd"
                >
                  添加
                </el-button>
                <el-button
                  v-auth="['dept/zzrysc']"
                  icon="remove"
                  type="danger"
                  @click="handleStaffDelete"
                >
                  批量删除
                </el-button>
              </vab-query-form-left-panel>
            </vab-query-form>
            <el-table
              ref="tableRef"
              v-loading="staffTable.loading"
              border
              stripe
              :data="staffTable.dataList"
              :height="staffTable.height"
              :cell-style="tableStyle.cellStyle"
              :header-cell-style="tableStyle.headerCellStyle"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange"
              @row-click="handleRowClick"
            >
              <el-table-column
                align="center"
                show-overflow-tooltip
                type="selection"
                width="60"
              />
              <el-table-column label="序号" type="index" width="60">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                :formatter="formatBingUser"
                label="用户账号"
                prop="user"
                width="100"
              />
              <el-table-column
                align="center"
                label="员工姓名"
                prop="userName"
                width="100"
              />
              <el-table-column
                align="center"
                label="员工编号"
                prop="labor"
                width="100"
              />
              <el-table-column
                align="center"
                label="手机号码"
                prop="mobilePhone"
                width="120"
              />
              <el-table-column
                align="center"
                label="员工状态"
                prop="statusDesc"
                width="100"
              />
              <el-table-column
                align="center"
                label="所属部门"
                prop="deptNames"
                width="160"
              />
              <el-table-column
                align="center"
                label="主部门"
                prop="mainDeptName"
                width="100"
              />
              <el-table-column
                align="center"
                label="部门领导"
                prop="leaderDesc"
                width="100"
              />
              <el-table-column
                align="center"
                label="职位"
                prop="positionName"
                width="120"
              />
              <el-table-column
                align="center"
                label="岗位"
                prop="jobName"
                width="120"
              />
              <el-table-column
                align="center"
                label="员工性别"
                prop="userSexDesc"
                width="90"
              />
              <el-table-column
                align="center"
                label="办公电话"
                prop="telephone"
                width="120"
              />
              <el-table-column
                align="center"
                label="员工来源"
                prop="userSourceDesc"
                width="90"
              />
              <el-table-column
                align="center"
                label="身份证号"
                prop="certNo"
                width="120"
              />
              <el-table-column
                align="center"
                label="电子邮箱"
                prop="email"
                width="100"
              />
              <el-table-column
                align="center"
                label="联系地址"
                prop="address"
                width="100"
              />
              <el-table-column
                align="center"
                :formatter="dateFormat"
                label="创建时间"
                prop="createTime"
                width="120"
              />
              <el-table-column
                align="center"
                label="备注"
                prop="remark"
                width="180"
              />
              <el-table-column
                align="center"
                fixed="right"
                label="操作"
                prop="operation"
                width="200"
              >
                <template #default="{ row }">
                  <el-row justify="start">
                    <el-col :span="12">
                      <el-button
                        v-auth="['dept/cjzh']"
                        size="small"
                        type="success"
                        @click="handleUserAdd(row)"
                      >
                        创建账号
                      </el-button>
                    </el-col>
                    <el-col :span="12">
                      <el-button
                        size="small"
                        type="primary"
                        @click="handleStaffDetail(row)"
                        >员工详情</el-button
                      >
                    </el-col>
                    <el-col :span="12">
                      <el-button
                        v-auth="['dept/zzryxg']"
                        size="small"
                        type="warning"
                        @click="handleStaffEdit(row)"
                      >
                        编辑员工
                      </el-button>
                    </el-col>
                    <el-col :span="12">
                      <el-button
                        v-auth="['dept/zzrysc']"
                        size="small"
                        type="danger"
                        @click="handleStaffDelete(row)"
                      >
                        删除员工
                      </el-button>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              :current-page="staffTable.pagination.current"
              :layout="staffTable.pagination.layout"
              :page-size="staffTable.pagination.size"
              :total="staffTable.pagination.total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <staff-edit ref="staffEditRef" width="60%" @confirm="queryTableData" />
    <user-edit ref="userEditRef" width="60%" @confirm="queryTableData" />
    <dept-selector ref="deptTreePickerRef" @change="handleDeptSelector" />
    <StaffPicker ref="staffPickerRef" @change="handleLeaderUserChange" />
  </div>
</template>
<script setup name="Dept" lang="ts">
import { useMessage, useMessageBox } from "@/hooks/message";
import pinyin from "js-pinyin";
import {
  queryDeptTree,
  deleteDept,
  updateDept,
  addDept
} from "@/api/admin/org/dept/";
import { deleteStaff, queryStaffTable } from "@/api/admin/org/staff/";
import { dateFormat } from "@/utils/common";
import { getTableHeight } from "@/utils/util";
import DeptSelector from "@/components/deptTreePicker.vue";
import StaffEdit from "./components/staffEdit.vue";
import UserEdit from "../sysuser/components/userEdit.vue";
import DictSelect from "@/components/dictSelect.vue";
import { BasicTree, useTree } from "@/hooks/tree";
import { BasicTableProps, useTable } from "@/hooks/table";

const state = reactive({
  searchKey: "",
  deptFormData: {
    id: "",
    deptCode: "",
    deptType: "0",
    pid: "0",
    parentDeptName: "",
    orderId: 0,
    deptLevel: 0,
    deptFullId: "",
    tel: "",
    address: "",
    remark: "",
    deptName: "",
    leaderUserId: "",
    leaderUserName: "",
    codeAsId: true
  },
  currentTabs: "0",
  deptFormRules: {
    deptName: [
      { required: true, message: "组织名称不能为空", trigger: "blur" }
    ],
    deptCode: [
      { required: true, message: "组织编码不能为空", trigger: "blur" }
    ],
    deptType: [{ required: true, message: "组织类型不能为空", trigger: "blur" }]
  }
});

const tabsRef = ref(null);
const staffEditRef = ref(null);
const userEditRef = ref(null);
const deptTreePickerRef = ref(null);
const staffPickerRef = ref(null);
const deptFormRef = ref(null);
const deptTypeRef = ref(null);
const deptTreeRef = ref(null);
const tableRef = ref(null);
const tableOptions = reactive<BasicTableProps>({
  height: getTableHeight(1, true, true) - 60 - 10,
  autoLoad: true,
  queryForm: {
    userName: "",
    labor: "",
    status: "ALL",
    mobilePhone: "",
    deptFullId: ""
  },
  queryFunction: queryStaffTable,
  descs: ["create_time"]
});

const {
  instance: staffTable,
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange,
  handleToggleHeight
} = useTable(tableOptions, tableRef);

const treeOptions = reactive<BasicTree>({
  queryForm: { pid: "0" },
  props: {
    children: "children",
    label: "text",
    isLeaf: "leaf"
  },
  queryFunction: queryDeptTree
});

const {
  instance: deptTree,
  queryTreeData,
  lazyLoadNode
} = useTree(treeOptions);

onMounted(() => {
  handleToggleHeight(10);
  queryTreeData();
});

const handleHeight = () => {
  staffTable.height = getTableHeight(1, true, true) - 40;
};

const handleOpenLeaderUserPicker = () => {
  staffPickerRef.value.show({ mainDeptId: state.deptFormData.id });
};

const handleLeaderUserChange = rows => {
  state.deptFormData.leaderUserName = rows[0].userName;
  state.deptFormData.leaderUserId = rows[0].id;
};

const handleSearchQuery = async () => {
  if (state.searchKey) {
    queryTreeData({ pid: null, searchKey: state.searchKey });
  } else {
    queryTreeData({ pid: "0", searchKey: null });
  }
};

const handleStatusChange = val => {
  staffTable.queryForm.status = val;
  queryTableData();
};

const openDeptSelector = () => {
  deptTreePickerRef.value.show();
};

const handleDeptSelector = node => {
  state.deptFormData.pid = node.id;
  state.deptFormData.parentDeptName = node.text;
  if (node.deptLevel) {
    state.deptFormData.deptLevel = parseInt(node.deptLevel) + 1;
  }
};

const handleDeptTypeChange = val => {
  state.deptFormData.deptType = val;
};

const handleStaffAdd = () => {
  staffEditRef.value.show();
};

const handleStaffEdit = row => {
  if (row.id) {
    staffEditRef.value.show(row, false);
  } else {
    useMessage().error("未选中任何行");
  }
};

const handleStaffDetail = row => {
  if (row.id) {
    staffEditRef.value.show(row, true);
  } else {
    useMessage().error("未选中任何行");
  }
};

const handleNodeClick = data => {
  state.deptFormData.id = data.id;
  state.deptFormData.deptName = data.text;
  state.deptFormData.deptCode = data.deptCode;
  state.deptFormData.deptType = data.deptType;
  state.deptFormData.tel = data.tel;
  state.deptFormData.address = data.address;
  state.deptFormData.remark = data.remark;
  state.deptFormData.orderId = data.orderId;
  state.deptFormData.pid = data.pid;
  state.deptFormData.parentDeptName = data.parentDeptName;
  state.deptFormData.leaderUserName = data.leaderUserName;
  staffTable.queryForm.deptFullId = state.deptFormData.id;
  queryTableData();
};

const handleDeptDelete = () => {
  const checkedNodes = deptTreeRef.value.getCheckedNodes();
  if (checkedNodes.length < 1) {
    useMessage().error("未选中任何组织");
  } else {
    useMessageBox()
      .confirm("删除的组织将无法恢复，是否继续")
      .then(async () => {
        const ids = checkedNodes.map(item => item.id).join();
        const { code, msg } = await deleteDept(ids);
        if (code && code === 200) {
          useMessage().success(msg);
          queryTreeData();
        } else {
          useMessage().error(msg);
        }
      });
  }
};

const handleStaffDelete = row => {
  let ids = null;
  if (row && row.id) {
    ids = row.id;
  } else {
    if (staffTable.dataSelections.length > 0) {
      ids = staffTable.dataSelections.map(item => item.id).join();
    } else {
      useMessage().error("未选中任何行");
    }
  }
  useMessageBox()
    .confirm("是否确认删除员工")
    .then(async () => {
      const { code, msg } = await deleteStaff(ids);
      if (code && code === 200) {
        useMessage().success(msg);
        await queryTableData();
      } else {
        useMessage().error(msg);
      }
    });
};

const handleDeptAdd = () => {
  deptFormRef.value.resetFields();
  state.deptFormData = {
    id: "",
    deptCode: "",
    deptType: "0",
    pid: "0",
    parentDeptName: "",
    orderId: 0,
    deptLevel: 0,
    deptFullId: "",
    tel: "",
    address: "",
    remark: "",
    deptName: "",
    leaderUserId: "",
    leaderUserName: "",
    codeAsId: true
  };
  state.currentTabs = "0";
};

const onDeptSaveSubmit = () => {
  deptFormRef.value.validate(async valid => {
    if (valid) {
      let res;
      if (state.deptFormData.id) {
        res = await updateDept(state.deptFormData);
      } else {
        res = await addDept(state.deptFormData);
      }
      console.log("res", res);
      if (res.code === 200) {
        state.deptFormData.id = res.data.id;
        useMessage().success(res.msg);
        queryTreeData();
      } else {
        useMessage().error(res.msg);
      }
    }
  });
};

const handleDeptNameChange = val => {
  if (!state.deptFormData.deptCode) {
    const deptCode = pinyin.getCamelChars(val).toUpperCase();
    state.deptFormData.deptCode = deptCode;
  }
};

const formatBingUser = row => {
  if (row.sysUser) {
    return "已创建";
  } else {
    return "未创建";
  }
};

const handleUserAdd = row => {
  if (row.sysUser) {
    useMessage().warning("员工账号已创建");
    return;
  }
  const sysUser = {
    id: row.id,
    userType: "1",
    userName: row.userName,
    phone: row.mobilePhone,
    labor: row.labor,
    mainDeptId: row.mainDeptId,
    mainDeptName: row.mainDeptName,
    status: row.status,
    password: "Itsm@123"
  };
  userEditRef.value.show(sysUser, "add");
};

onBeforeMount(() => {
  window.addEventListener("resize", handleHeight);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleHeight);
});
</script>

<style lang="scss"></style>
